package com.enba.boot.openfeign.interceptor;

import com.enba.boot.openfeign.extend.RequestTemplateExtend;
import com.enba.boot.openfeign.properties.OpenFeignProperties;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import java.util.Enumeration;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/** 自定义拦截器：在每次请求发送前添加通用的认证信息、日志记录等。 */
public class FeignRequestInterceptor implements RequestInterceptor {

  private final OpenFeignProperties openFeignProperties;
  private final RequestTemplateExtend requestTemplateExtend;

  public FeignRequestInterceptor(
      OpenFeignProperties openFeignProperties, RequestTemplateExtend requestTemplateExtend) {
    this.openFeignProperties = openFeignProperties;
    this.requestTemplateExtend = requestTemplateExtend;
  }

  @Override
  public void apply(RequestTemplate requestTemplate) {
    if (openFeignProperties.isEnabled()) {
      // 传递请求来源
      requestTemplate.header("fromSource", openFeignProperties.getFromSource());

      ServletRequestAttributes attributes =
          (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
      if (attributes != null) {
        HttpServletRequest request = attributes.getRequest();
        Enumeration<String> headerNames = request.getHeaderNames();
        if (headerNames != null) {
          while (headerNames.hasMoreElements()) {
            String name = headerNames.nextElement();
            if (openFeignProperties.getTokenHeaderName().equals(name)) {
              // 传递token
              requestTemplate.header(name, request.getHeader(name));
            }

            if (openFeignProperties.getTraceId().equals(name)) {
              // 传递traceId
              requestTemplate.header(name, request.getHeader(name));
            }
          }
        }
      }

      // 扩展RequestTemplate
      requestTemplateExtend.requestTemplateExtend(requestTemplate);
    }
  }
}
